#!/usr/bin/env python3
import json
import os
import argparse
import sys
import AutoExecUtils
import VsphereQuery


def usage():
    pname = os.path.basename(__file__)
    print(pname + " --ip <vcenter ip> --user <user> --password <password> ")
    exit(1)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--ip", default="", help="vcenter管理IP")
    parser.add_argument("--port", default="443", help="vcenter管理端口")
    parser.add_argument("--user", default="", help="vcenter console login user")
    parser.add_argument("--password", default="", help="vcenter console login user password")
    parser.add_argument("--verbose", default="0", help="verbose output")
    args = parser.parse_args()

    ip = args.ip
    user = args.user
    password = args.password
    port = args.port
    isVerbose = int(args.verbose)
    node = os.getenv("AUTOEXEC_NODE")
    if node != None and node != "":
        node = json.loads(node)

    if (ip == None or ip == "" or user == None or user == "" or password == None or password == "") and (node == None or node == ""):
        usage()

    if (ip == None or ip == "" or user == None or user == "" or password == "" or password == None) and node != None:
        ip = node["host"]
        port = node["port"]
        if port is None or port == "":
            port = node["protocolPort"]
        user = node["username"]
        password = node["password"]

    data = []
    vc = VsphereQuery.VsphereQuery(ip, user, password, port)
    result = vc.collect()

    novmtools = []
    for dc in result["DATACENTER"]:
        dc["_OBJ_CATEGORY"] = "VIRTUALIZED"
        dc["_OBJ_TYPE"] = "VIRTUALIZED-DATACENTER"
        clusters = dc["CLUSTER"]
        for cluster in clusters:
            cluster["_OBJ_CATEGORY"] = "VIRTUALIZED"
            cluster["_OBJ_TYPE"] = "VIRTUALIZED-CLUSTER"
            cluster["VIRT_PLATFORM"] = "vmware"
            # 物理机信息
            hosts = cluster["HOST"]
            rel_host = []
            if hosts != None and len(hosts) > 0:
                for host in hosts:
                    host["MGMT_IP"] = host["NAME"]
                    host["MGMT_PORT"] = 22
                    host["VCENTER_IP"] = ip
                    host["_OBJ_CATEGORY"] = "HOST"
                    # 保存和主机采集的PK一致
                    host["PK"] = ["BOARD_SERIAL"]
                    data.append(host)
                    BOARD_SERIAL = host["BOARD_SERIAL"]
                    if BOARD_SERIAL is None:
                        BOARD_SERIAL = ""
                    rel_host.append(
                        {
                            "_OBJ_CATEGORY": "HOST",
                            "_OBJ_TYPE": "HOST",
                            "UUID": host["UUID"],
                            "BOARD_SERIAL": BOARD_SERIAL,
                            "HOST_IP": host["HOST_IP"],
                        }
                    )
            cluster["CONTAIN_HOST"] = rel_host
            del cluster["HOST"]

            # 操作系统信息
            vms = cluster["VM"]
            rel_vms = []
            if vms != None and len(vms) > 0:
                for vm in vms:
                    vm_ip = vm["IP"]
                    if vm_ip == None or vm_ip == "":
                        novmtools.append(vm)
                    else:
                        vm["MGMT_IP"] = vm["IP"]
                        vm["MGMT_PORT"] = 22
                        vm["VCENTER_IP"] = ip
                        vm["_OBJ_CATEGORY"] = "OS"
                        vm["_OBJ_TYPE"] = vm["OS_TYPE"]
                        # 保持和主机采集的PK一致
                        vm["PK"] = ["MGMT_IP"]
                        data.append(vm)
                        rel_vms.append({"_OBJ_CATEGORY": "OS", "_OBJ_TYPE": vm["OS_TYPE"], "MGMT_IP": vm["IP"], "VM_ID": vm["VM_ID"], "HOST_ON": vm["HOST_ON"], "UUID": vm["UUID"]})

            cluster["CONTAIN_VMS"] = rel_vms
            del cluster["VM"]

    # 虚拟化信息
    result["MGMT_IP"] = ip
    result["MGMT_PORT"] = port
    result["_OBJ_CATEGORY"] = "VIRTUALIZED"
    result["_OBJ_TYPE"] = "VCENTER"
    result["VIRT_PLATFORM"] = "vmware"
    result["PK"] = ["MGMT_IP"]
    data.append(result)

    # 未安装vmtools工具的vms
    for vm in novmtools:
        vm["VCENTER_IP"] = ip
        vm["_OBJ_CATEGORY"] = "NOVMTOOL"
        vm["_OBJ_TYPE"] = "OS"
        vm["OS_TYPE"] = "OS"
        vm["PK"] = ["VCENTER_IP", "VM_ID"]
        data.append(vm)

    # print(json.dumps(data))
    # 定义插件的输出变量output
    out = {}
    out["DATA"] = data
    AutoExecUtils.saveOutput(out)

    if isVerbose == 1:
        print("==================\n")
        print(json.dumps(data))
        print("==================\n")
